package rocket.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import rocket.client.Client;
import rocket.logs.Write;
import rocket.logs.WriteType;

/**
 * @author justin
 * @version
 *creates a server instance that listens on port whatever
 */
public class Server {

	private ServerSocket server;

	private Socket client;

	private BufferedReader in;
	
	private PrintWriter out;
	
	private String line;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Server s = new Server();
		Client c = new Client();

		writeLog("Server Started");
		
		s.listenSocket();
		c.listenSocket();
	}

	/**
	 * 
	 */
	public void listenSocket() {

		try {
			server = new ServerSocket(1337);
		} catch (IOException e) {
			writeLog(e.getMessage());
		}

		try {
			client = server.accept();
		} catch (IOException e) {
			writeLog(e.getMessage());
		}
		
		try {
			in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			out = new PrintWriter(client.getOutputStream(), true);
		} catch (IOException e) {
			writeLog(e.getMessage());
		}
		
		while(true) {
			try {
				line = in.readLine();
				out.println(line);
			} catch (IOException e) {
				writeLog(e.getMessage());
			}
		}

		
	}  
	
	/**
	 * @param s
	 */
	public static void writeLog(String s){
		new Write(WriteType.SERVER, s);
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Object#finalize()
	 */
	protected void finalize(){
	//Objects created in run method are finalized when 
	//program terminates and thread exits
	     try{
	        server.close();
			writeLog("Server Offline");
	    } catch (IOException e) {
	        System.out.println("Could not close socket");
			writeLog(e.getMessage());
	        System.exit(-1);
	    }
	  }
	
	public String toString(){
		return "";
	}

}
